package com.cheng.mybatis.serviceImpl;

import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cheng.mybatis.domain.Book;
import com.cheng.mybatis.domain.BookExample;
import com.cheng.mybatis.domain.Bookdetailed;
import com.cheng.mybatis.domain.BookdetailedExample;
import com.cheng.mybatis.mapper.BookMapper;
import com.cheng.mybatis.mapper.BookdetailedMapper;
import com.cheng.mybatis.service.BookService;

@Service
public class BookServiceImpl implements BookService {

	@Autowired
	private BookMapper mapper;

	@Autowired
	private BookdetailedMapper mapper2;

	public List<Book> showAll() {
		BookExample example = new BookExample();
		List<Book> lists = mapper.selectByExample(example);

		return lists;
	}

	public List<Book> serachByName(String bname) {

		BookExample example = new BookExample();

		example.createCriteria().andBnameEqualTo(bname);

		List<Book> lists = mapper.selectByExample(example);

		return lists;
	}

	public List<Book> addBook(Book book, Bookdetailed bookdetailed) {

		UUID randomUUID = UUID.randomUUID();
		book.setNumber(randomUUID.toString());
		int insert = mapper.insert(book);

		bookdetailed.setNumber(book.getNumber());
		mapper2.insert(bookdetailed);

		System.out.println(insert);

		List<Book> books = showAll();
		return books;

	}

	public List<Book> deleteBook(String number) {
		BookExample example = new BookExample();
		example.createCriteria().andNumberEqualTo(number);
		mapper.deleteByExample(example);
		List<Book> books = showAll();
		return books;
	}

	public Book serachByNumber(String number) {

		BookExample example = new BookExample();
		example.createCriteria().andNumberEqualTo(number);
		List<Book> books = mapper.selectByExample(example);
		if (books != null && books.size() > 0) {
			Book book = books.get(0);
			return book;
		}
		return null;
	}

	public Bookdetailed serachByNumber2(String number) {

		BookdetailedExample example2 = new BookdetailedExample();
		example2.createCriteria().andNumberEqualTo(number);
		List<Bookdetailed> bookdetaileds = mapper2.selectByExample(example2);
		if (bookdetaileds != null && bookdetaileds.size() > 0) {
			Bookdetailed bookdetailed = bookdetaileds.get(0);
			return bookdetailed;
		}
		return null;
	}

	public List<Book> updateBook(Book book) {

		BookExample example = new BookExample();
		example.createCriteria().andNumberEqualTo(book.getNumber());

		mapper.updateByExampleSelective(book, example);

		List<Book> books = showAll();
		return books;
	}

}
